import type {ToolsReqData, ToolSearchParams, ToolsInfo} from '@/components/Tools/tools.type.ts'
import { toolsConfig, getAllTools } from './tools-config'

//获取tools分类与对应的工具
export function getToolsCate() {
    return toolsConfig
}

//工具list
export function toolsList() {
    return getAllTools()
}

/**
 * url为键名的工具list map
 * @returns
 */
export function urlKeyMap() {
    const toolsMapByUrlKey = new Map()
    const list = toolsList()
    for (const tool of list) {
        toolsMapByUrlKey.set(tool.url, tool)
    }
    return toolsMapByUrlKey
}

//获取工具（保持向后兼容）
export function getTools(data: ToolsReqData): ToolsInfo[] {
    return searchTools({
        cateId: data.cateId > 0 ? data.cateId : undefined,
        title: data.title || undefined
    })
}

//增强的工具搜索功能
export function searchTools(params: ToolSearchParams = {}): ToolsInfo[] {
    const {cateId, title, keyword} = params
    let list = toolsList()
    
    //分类筛选
    if (cateId && cateId > 0) {
        list = list.filter(item => item.cateId === cateId)
    }
    
    //标题筛选
    if (title && title.trim() !== '') {
        const searchTerm = title.toLowerCase().trim()
        list = list.filter(item => {
            const titleMatch = item.title.toLowerCase().includes(searchTerm)
            const descMatch = item.desc.toLowerCase().includes(searchTerm)
            return titleMatch || descMatch
        })
    }
    
    //关键词筛选
    if (keyword && keyword.trim() !== '') {
        const searchTerm = keyword.toLowerCase().trim()
        list = list.filter(item => {
            const titleMatch = item.title.toLowerCase().includes(searchTerm)
            const descMatch = item.desc.toLowerCase().includes(searchTerm)
            const keywordsMatch = item.meta.keywords.toLowerCase().includes(searchTerm)
            return titleMatch || descMatch || keywordsMatch
        })
    }
    
    return list
}

//根据ID获取工具
export function getToolById(id: string): ToolsInfo | undefined {
    return getAllTools().find(tool => tool.id === id)
}

const ToolsExport = {
    getTools,
    getToolsCate,
    toolsList,
    searchTools,
    getToolById,
};

export default ToolsExport;